package com.simba.server.base;

import com.simba.server.components.data.DeleteData;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by kavin on 16-3-31.
 */
public class TimeUtil
{
	private TimeUtil(){}
	private static final Object lock = new Object();
	private static final Map<String, ThreadLocal<DateFormat>> formats = new HashMap<>();
	private static final String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm:ss";

	public static DeleteData getDeleteTimestamp(int restoreDays)
	{
		long restoreTime = restoreDays * 24 * 3600 * 1000L;

		Timestamp deleteTime = new Timestamp(System.currentTimeMillis() - restoreTime);
		DeleteData deleteData = new DeleteData();
		deleteData.setDeleteBeforeTime(deleteTime);

		return deleteData;
	}

	private static DateFormat getFormat(final String pattern){
		ThreadLocal<DateFormat> local = formats.get(pattern);
		if (local == null) {
			synchronized (lock) {
				local = formats.get(pattern);
				if (local == null) {
					local = ThreadLocal.withInitial(() -> new SimpleDateFormat(pattern));
					formats.put(pattern, local);
				}
			}
		}
		return local.get();
	}

	public static String getTimeDateString(String format, Date date)
	{
		if (CommonUtil.isNull(format))
			format = TimeUtil.DEFAULT_PATTERN;

		return getFormat(format).format(date);
	}

	public static String getTimeDateString(String fromFormat, String toFormat, String date)
	{
		if (CommonUtil.isNull(fromFormat))
			fromFormat = TimeUtil.DEFAULT_PATTERN;
		if (CommonUtil.isNull(toFormat))
			toFormat = TimeUtil.DEFAULT_PATTERN;

		String toDate;
		try
		{
			toDate = getFormat(toFormat).format(getFormat(fromFormat).parse(date));
		}
		catch (Exception e)
		{
			toDate = "1980-00-00 00:00:00";
		}
		return toDate;
	}

	public static long getTimeDifference(String time1, String time2)
	{
		try
		{
			SimpleDateFormat format = new SimpleDateFormat(TimeUtil.DEFAULT_PATTERN);
			Date beginTime = format.parse(time1);
			Date endTime = format.parse(time2);
			long between = (endTime.getTime() - beginTime.getTime()) / 1000;
			long minute = between / 60;
			if (between % 60 != 0)
			{
				minute += 1;
			}
			return minute;
		}
		catch (Exception ex)
		{
			return 0;
		}
	}
}
